package megrez.oss.common;

import java.util.Arrays;

import lombok.experimental.UtilityClass;

/**
 * 文件名工具
 * 
 * @author Lucky Yang
 * @since 0.0.1
 */
@UtilityClass
public class FileNameHelper {
    public static final int MASK = 255;
    protected static final Character[] INVALID_SPECIFIC_CHARS = {'"', '*', '<', '>', '?', '|', '\000'}; 

    /**
     * 判定文件名是否合法
     * 
     * @param fileName
     * @return
     */
    public boolean validate(String fileName) {
        if (fileName == null || fileName.isEmpty() || fileName.length() > 255) {
            return false;
        }
        return Arrays.stream(INVALID_SPECIFIC_CHARS)
          .noneMatch(ch -> fileName.contains(ch.toString()));
    }

    /**
     * 根据文件名的Hash值，生产两个目录名
     * 
     * @param fileName
     * @return
     */
    public Pair<String, String> generalHashPath(String fileName) {
        final int hash = fileName.hashCode();
        final int firstDir = hash & MASK;
        final int secondDir = (hash >> 8) & MASK;

        return Pair.with(String.format("%02x", firstDir).toUpperCase(),
                String.format("%02x", secondDir).toUpperCase());
    }
}
